package com.jj.service.room;

import com.jj.battle.protocol.GameProto;
import io.undertow.util.CopyOnWriteMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;


/**
 * Copyrights: QidianGroup@JJ
 *
 * @author: LuHan
 * @date: 2018/1/15, 16:36
 */
public class BattleRecordManager {
    private static Logger logger = LoggerFactory.getLogger(BattleRecordManager.class);

    List<BattleRecord> recorders = new LinkedList<>();

    /**
     * 记录操作
     * TODO: D.O.S. 攻击
     * @param uid
     * @param cmd
     */
    public void addOperation(Long uid, GameProto.PKG_OPERATION cmd){
        BattleRecord record = null;
        if(recorders.size() == 0){
            recorders.add(new BattleRecord());
        }
        record = recorders.get(recorders.size()-1);
        record.addCommand(uid, cmd);
    }

    public void updateNewFrame(){
        recorders.add(new BattleRecord());
    }

    public GameProto.PKG_FRAME getPkgFrame(int frameNum) {
        BattleRecord record = recorders.get(recorders.size()-1);
        if(record != null){
            List<GameProto.DT_FRAME_CONTENT > contents = record.getContent();
            GameProto.PKG_FRAME.Builder bld = GameProto.PKG_FRAME.newBuilder();
            bld.setFrameNo(frameNum);
            for(GameProto.DT_FRAME_CONTENT content: contents){
                if(content != null) {
                    bld.addOperations(content);
                }else{
                    GameProto.DT_FRAME_CONTENT.Builder b = GameProto.DT_FRAME_CONTENT.newBuilder();
                    b.setPlayerId(0L);
                    b.setOperation(GameProto.PKG_OPERATION.newBuilder().build());
                    bld.addOperations(b.build());
                    logger.debug("get null op at {}, total:{}", frameNum, contents.size());
                }
            }
            return bld.build();
        }else{
            return null;
        }
    }

    public GameProto.PKG_SYN_STATE_NTF getSynState(int beginSeq){
        GameProto.PKG_SYN_STATE_NTF.Builder bld = GameProto.PKG_SYN_STATE_NTF.newBuilder();
        for(int i = beginSeq; i<=recorders.size(); i++){
            BattleRecord record = recorders.get(i);
            if(record != null){
                GameProto.PKG_FRAME frame = getPkgFrame(i);
                logger.debug("get pkt frame:{}", frame);
                bld.addFrames(frame);
                logger.debug("add frame: {} -> {}", i, frame);
            }else{
                logger.debug("ignore empty record {}", i);
            }
        }
        return bld.build();
    }
}
